package com.shouer.doc.ui.modifypass.presenter;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.shouer.doc.common.ShouerConst;
import com.shouer.doc.request.GsonRequest;
import com.shouer.doc.request.RequestUtil;
import com.shouer.doc.ui.modifypass.response.ModifyPassResponse;
import com.shouer.doc.ui.modifypass.view.IModifyPassView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by ZXL on 2016/12/5.
 */

public class ModifyPassPresenterCompl implements IModifyPassPresenter {

    private IModifyPassView resetPassView;

    public ModifyPassPresenterCompl(IModifyPassView resetPassView) {
        this.resetPassView = resetPassView;
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        resetPassView=null;
    }

    @Override
    public void modifyPassword(String oldPassword, String newPassword) {
        Map<String, String> param = new HashMap<>();
        param.put("userId", resetPassView.getApp().getUserModel().getUserId());
        param.put("oldPassword", oldPassword);
        param.put("password", newPassword);
        param.put("operType", "2");
        param.put("loginFlag", "2");

        final GsonRequest<ModifyPassResponse> request = new GsonRequest(ShouerConst.APP_SERVER_https,"modifyPassword", ModifyPassResponse.class, new Response.Listener<ModifyPassResponse>() {
            @Override
            public void onResponse(ModifyPassResponse response) {
                EventBus.getDefault().post(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                resetPassView.modifyPassFailed("修改密码失败 网络异常");
            }
        });

        RequestUtil.sendRequest(resetPassView.getContext(), param, request);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(ModifyPassResponse response)
    {
        if (response.getErrorCode()>=0)
        {
            resetPassView.modifyPassSuccess();
        }else
        {
            resetPassView.modifyPassFailed(response.getErrorMsg());
        }
    }
}
